from flask import Flask, request, jsonify, render_template, abort

app = Flask(__name__)

# ------------------------------
# 用 dict 模拟数据库
# key 为自增整数，value 为字典对象
# ------------------------------
db = {}
next_id = 1   # 自增主键

# ------------------------------
# 路由：首页
# ------------------------------
@app.route('/')
def index():
    return render_template('index.html')

# ------------------------------
# 接口：列表 + 条件查询
# ------------------------------
@app.route('/api/users', methods=['GET'])
def list_users():
    """
    支持按 name 模糊查询
    例：/api/users?name=Tom
    """
    name_filter = request.args.get('name', '').strip().lower()
    items = [
        {'id': uid, **info}
        for uid, info in db.items()
        if not name_filter or name_filter in info['name'].lower()
    ]
    return jsonify(items)

# ------------------------------
# 接口：单条查询
# ------------------------------
@app.route('/api/users/<int:uid>', methods=['GET'])
def get_user(uid):
    if uid not in db:
        abort(404, description=f"user {uid} not found")
    return jsonify({'id': uid, **db[uid]})

# ------------------------------
# 接口：新增
# ------------------------------
@app.route('/api/users', methods=['POST'])
def create_user():
    global next_id
    data = request.get_json(force=True)
    if not data or 'name' not in data:
        return jsonify({'error': "`name` field required"}), 400

    record = {
        'name': data['name'].strip(),
        'age':  int(data.get('age', 0)),
        'city': data.get('city', '')
    }
    db[next_id] = record
    uid = next_id
    next_id += 1
    return jsonify({'id': uid, **record}), 201

# ------------------------------
# 接口：修改（全量更新）
# ------------------------------
@app.route('/api/users/<int:uid>', methods=['PUT'])
def update_user(uid):
    if uid not in db:
        abort(404, description=f"user {uid} not found")
    data = request.get_json(force=True)
    if not data:
        return jsonify({'error': "empty payload"}), 400

    db[uid]['name'] = data.get('name', db[uid]['name']).strip()
    db[uid]['age']  = int(data.get('age', db[uid]['age']))
    db[uid]['city'] = data.get('city', db[uid]['city'])
    return jsonify({'id': uid, **db[uid]})

# ------------------------------
# 接口：删除（可选）
# ------------------------------
@app.route('/api/users/<int:uid>', methods=['DELETE'])
def delete_user(uid):
    if uid not in db:
        abort(404, description=f"user {uid} not found")
    del db[uid]
    return '', 204

# ------------------------------
# 错误处理
# ------------------------------
@app.errorhandler(404)
def not_found(err):
    return jsonify({'error': str(err.description)}), 404

# ------------------------------
# 启动
# ------------------------------
if __name__ == '__main__':
    app.run(debug=True)